from django.conf import settings
from django.shortcuts import render

# Create your views here.
# /test/
from django.views import View

from itsdangerous import TimedJSONWebSignatureSerializer, BadData
from rest_framework import mixins
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from users import serializers
from users.models import User
from users.serializers import CreateUserSerializer, UserDetailSerializer, UserAddressSerializer


class TestView(View):

    def get(self, request):
        return render(request, 'test.html')


class TestView2(APIView):

    def get(self, request):
        # b = 1/0
        response = Response({'message': 'get请求！'})

        # 解决跨域问题方式1
        # response['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8080'
        return response

    def post(self, request):
        response = Response({'message': 'post请求！'})

        # 解决跨域问题方式
        # response['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8080'
        return response


class UsernameCountView(APIView):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        data = {
            'username': username,
            'count': count
        }
        return Response(data)


class CreateUserView(CreateAPIView):
    """注册用户"""

    serializer_class = CreateUserSerializer


class UserView(RetrieveAPIView):
    """查询一条用户详情数据"""

    serializer_class = UserDetailSerializer
    # 登录才能调用此接口
    permission_classes = [IsAuthenticated]
    # queryset = User.objects.all()

    # 重写父类的方法, 获取用户对象
    def get_object(self):
        # 要查询的用户数据
        return self.request.user


class EmailView(UpdateAPIView):  # 保存用户邮箱# email

    permission_classes = [IsAuthenticated]
    serializer_class = serializers.EmailSerializer

    def get_object(self):
        return self.request.user


class VerifyEmailView(APIView):  # 激活用户邮箱
    def get(self, request):
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=400)

        serializer = TimedJSONWebSignatureSerializer(
            settings.SECRET_KEY, expires_in=60 * 60 * 24)
        try:
            data = serializer.loads(token)
        except BadData:
            return Response({'message': '链接信息无效'}, status=400)

        email = data.get('email')  # 查询要激活用户对象
        user_id = data.get('user_id')
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return Response({'message': '激活用户不存在'}, status=400)

        user.email_active = True  # 修改用户邮箱激活状态
        user.save()

        return Response({'message': 'OK'})


class AddressViewSet(mixins.CreateModelMixin, GenericViewSet):

    serializer_class = UserAddressSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        # 返回当前登录用户所有的地址
        return self.request.user.addresses.filter(is_deleted=False)

    def create(self, request, *args, **kwargs):
        count = request.user.addresses.count()
        if count >= 2:
            return Response({'message': '地址个数已达到上限'}, status=400)

        return super().create(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):

        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'user_id': request.user.id,
            'default_address_id': request.user.default_address_id,
            'limit': 10,
            'addresses': serializer.data
        })

    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

        # put /addresses/pk/status/

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

